// 引入第三方包
// var createError = require("http-errors");
require("express-async-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
const { expressjwt } = require("express-jwt");
const resHandler = require("./middleware/resHandler");
const errHandler = require("./middleware/errHandler");
// 连接数据库
require("./dao/dbConnection");

// 注册全局插件
require("./plugins");

// 定义路由
const router = require("./router");

// 创建express应用
var app = express();

// 使用各种中间件
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// 启用静态资源服务器
app.use(express.static(path.join(__dirname, "public")));

// 响应中间件
app.use(resHandler);
// 使用解析jwt中间件
app.use(
  expressjwt({
    secret: process.env.JWT_SECRECT,
    algorithms: ["HS256"],
  }).unless({
    path: [
      { url: /^\/uploads\/.*/ },
      { url: "/favicon.ico", methods: ["GET"] },
      { url: "/api/user/login", methods: ["POST"] },
      { url: "/api/user/register", methods: ["POST"] },
    ],
  })
);
// 使用路由中间件
app.use("/api", router);
// 404错误我处理中间件
app.use(function (req, res, next) {
  res.send("404");
});
// 全局错误处理中间件
app.use(errHandler);

module.exports = app;
